/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.ui;

import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import net.worlds.Settings;


public class SettingsTable extends JTable{
    private SettingsTableModel model = new SettingsTableModel();
    public SettingsTable()
    {
        super();
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                initModel();
                getTableHeader().setReorderingAllowed(false);
                showSettings();
            }
        });
    }
    public void showSettings()
    {
        initModel();
        while(getModel().getRowCount() > 0)
        {
            getModel().removeRow(0);
        }
        for(String p : Settings.getAllSettings().keySet())
        {
           getModel().addRow(new Object[]{p, Settings.getAllSettings().get(p)});
        }
    }
    private void initModel()
    {
        model = new SettingsTableModel();
        setModel(model);
        model.addColumn("Name");
        model.addColumn("Value");
        getColumnModel().getColumn(1).setCellRenderer(new SettingsTableCellRenderer());
        getColumnModel().getColumn(0).setCellRenderer(new SettingsTableCellRenderer());
        getColumnModel().getColumn(1).setCellEditor(new SettingsTableCellEditor());
        getColumnModel().getColumn(0).setCellEditor(new SettingsTableCellEditor());
    }
    public void save()
    {
        ((SettingsTableCellEditor)getColumnModel().getColumn(1).getCellEditor()).stopCellEditing();
        for(int r = 0; r < getModel().getRowCount(); r++)
        {
            String key = getModel().getValueAt(r, 0).toString();
            Object value = getModel().getValueAt(r, 1);
            if(value != Settings.getAllSettings().get(key))
                Settings.set(key, value, true);
        }
    }
    @Override
    public DefaultTableModel getModel()
    {
        return model;
    }
}
